// import UseToken from "../../request/UseToken";
// import axios from "../../request/axios";
// import { useEffect, useState } from "react";
// import { useParams } from "react-router-dom";
// import { marked } from "marked";
// import { Flex, Input, Button } from "antd";

// const { TextArea } = Input;
// function Xiang() {
//   const { id } = useParams();
//   const [art, setArt] = useState([]);
//   useEffect(() => {
//     axios.get(`http://blogapi.shbwyz.com/article/${id}`).then((res) => {
//       // console.log(res);
//       setArt(res.data);
//     });
//   }, []);
//   UseToken();
//   return (
//     <div>
//       {/* {id} */}
//       <div
//         dangerouslySetInnerHTML={{ __html: marked(art.content || "") }}
//       ></div>
//       <Flex vertical gap={32}>
//         <TextArea
//           showCount
//           maxLength={100}
//           placeholder="请输入评论内容"
//           style={{ height: 120, width: 200 }}
//           onChange={(e) => {
//             console.log(e.target.value);
//           }}
//         />
//       </Flex>
//       <Button>提交评论</Button>
//     </div>
//   );
// }

// export default Xiang;
import React, { useEffect, useState } from "react";
import axios from "axios";
import "./Xiang.css";
import { useParams } from "react-router-dom";
import { marked } from "marked";
const sensitiveWords = ["傻子", "笨蛋"];
interface Comment {
  id: number;
  content: string;
  createdAt: string;
  user: { username: string };
  replies: { id: number; content: string; user: { username: string } }[];
}
interface Article {
  createdAt: string;
  updatedAt: string;
  id: number;
  title: string;
  content: string;
  viewCount: number;
  tags: { name: string }[];
  categories: { name: string }[];
  comments: Comment[];
}
const Xiang: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [article, setArticle] = useState<Article | null>(null);
  const [comment, setComment] = useState<string>("");
  const [message, setMessage] = useState<string>("");
  const [comments, setComments] = useState<Comment[]>([]);
  useEffect(() => {
    const fetchArticle = async () => {
      try {
        const response = await axios.get(
          `http://blogapi.shbwyz.com/article/${id}`
        );
        setArticle(response.data);
        setComments(response.data.comments);
      } catch (error) {
        console.error("Error fetching article:", error);
      }
    };
    if (id) {
      fetchArticle();
    }
  }, [id]);
  const handleCommentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setComment(e.target.value);
  };
  const filterSensitiveWords = (text: string) => {
    let filteredText = text;
    sensitiveWords.forEach((word) => {
      const regex = new RegExp(word, "gi");
      filteredText = filteredText.replace(regex, "*".repeat(word.length));
    });
    return filteredText;
  };
  const handleCommentSubmit = async () => {
    if (!comment) {
      setMessage("评论内容不能为空");
      return;
    }
    const filteredComment = filterSensitiveWords(comment);
    try {
      const params = {
        userId: 47529555,
        content: filteredComment,
        articleId: parseInt(id || "0"),
      };
      const response = await axios.post(
        "http://blogapi.shbwyz.com/discuss",
        params,
        {
          headers: {
            Authorization:
              "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3MzUyMDkzNjAsImV4cCI6MTczNzgwMTM2MH0.wI_YlirqF_DKrw0hSmDxoWDpJRlReaC84ohbf39fkJs",
          },
        }
      );
      if (response.status === 200) {
        setMessage("评论提交成功！");
        setComment("");
        setComments((prevComments) => [
          ...prevComments,
          {
            id: response.data.id,
            content: filteredComment,
            createdAt: new Date().toISOString(),
            user: { username: "当前用户" },
            replies: [],
          },
        ]);
      }
    } catch (error) {
      console.error("Error submitting comment:", error);
      setMessage("评论提交失败，请稍后再试");
    }
  };
  if (!article) {
    return <div>加载中...</div>;
  }
  return (
    <div>
      <div style={{ textAlign: "left" }}>
        <div
          dangerouslySetInnerHTML={{ __html: marked(article.content) }}
        ></div>
      </div>
      <div style={{ textAlign: "left" }}>
        <h3>发表评论</h3>
        <input
          type="text"
          value={comment}
          onChange={handleCommentChange}
          placeholder="输入评论内容"
          style={{ width: "200px", padding: "8px", margin: "10px" }}
        />
        <button onClick={handleCommentSubmit}>点击提交评论</button>
      </div>
      {message && <div>{message}</div>}
      <div style={{ marginTop: "10px" }} className="comment-list">
        {comments.length === 0 ? (
          <div>无评论</div>
        ) : (
          comments.map((comment) => (
            <div key={comment.id} style={{ marginBottom: "20px" }}>
              <div style={{ fontWeight: "bold" }}>{comment.user.username}</div>
              <div>{comment.content}</div>
              <div style={{ color: "gray", fontSize: "12px" }}>
                {new Date(comment.createdAt).toLocaleString()}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
};
export default Xiang;
